<?php

/**
 * Description of Test
 * 
 * @author anhducbkhn
 * @since Jul 25, 2013 - 4:40:48 PM
 */
class TestController extends MyController
{

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('ViewLogs', 'Chat', 'ApacheLogs', 'ProcessURL'),
                'users'   => array('*'),
            ),
        );
    }

    public function check_customer()
    {
        $customer = Customer::model()->findAll();

        if (NULL !== $customer)
        {
            foreach ($customer as $c)
            {

                //if user not found...
                if (NULL == $c->user)
                {
                    echo $c->id . '<br>';
                }
            }
        }
    }

    public function check_apt_customer()
    {
        $apt_customer = AptCustomer::model()->findAll();

        if ($apt_customer)
        {
            foreach ($apt_customer as $ac)
            {

                if (NULL == $ac->customer)
                {
                    echo 'can not find customer id: ' . $ac->id . '<br>';
                }

                if (NULL == $ac->appt)
                {
                    echo 'can not find appoinmnet id: ' . $ac->id . '<br>';
                }
            }
        }

        die('end');
    }

    public function check_order()
    {
        $order = Orders::model()->findAll();

        if ($order)
        {
            foreach ($order as $or)
            {
                if ($or->appoint == NULL)
                {
                    echo 'null appoinmnet id' . $or->order_id . '<br>';
                }

                if ($or->getCustomer() == NULL)
                {
                    echo 'Null customer id' . $or->order_id . '<br>';
                }
            }
        }

        die('xxx');
    }

    public function actionApacheLogs()
    {

        $this->check_order();

        die('end...');

//       $key=$_GET['key'];         
//       $order=  Orders::model()->findByAttributes(array('order_key'=>$key));
//       
//       if(!$order ){
//           die('not found order');
//       }
//       
//       $appointment=  Appoint::model()->findByPk($order->apt_id);
//       if(!$appointment ){
//           echo 'null appoinmnet <br>';
//       }else{
//           if($appointment->delete()){
//               echo 'delete appoinemnt successlly <br>';
//           }
//       }
//       
//       $appt_cus=  AptCustomer::model()->findByAttributes(array('apt_id'=>$order->apt_id ));
//       
//       if(!$appt_cus ){
//           echo 'null appt_cus <br>';
//       }else{
//           if($appt_cus->delete()){
//               echo 'delete successfully <br>';
//           }else{
//               echo 'can not delete'.$appt_cus->id; 
//           }
//       }
//       
//       if($order->delete() ){
//           echo 'delete order sucesfully <br>';
//       }else{
//           echo 'can not delete';
//       }
    }

    public function actionViewLogs()
    {
        $cus_id = $_GET['cus_id'];

        //find customer at tbl_customer
        $customer = Customer::model()->findByPk($cus_id);

        if (!$customer)
        {
            echo '1.not found customer...<br>';
        }
        else
        {
            //find appoinmnet
            $apt = AptCustomer::model()->findAllByAttributes(array('customer_id' => $customer->id));

            if (!$apt)
            {
                echo '2. apt not found ...<br>';
            }
            else
            {
                foreach ($apt as $value)
                {
                    //find order
                    $oder = Orders::model()->findByAttributes(array('apt_id' => $value->apt_id));
                    if ($oder)
                    {
                        if ($oder->delete())
                        {
                            echo '3. delete order...<br>';
                        }
                    }

                    if ($value->delete())
                    {
                        echo '4. delete appoinmnt <br>';
                    }

                    $apt = $value->appt;
                    if ($apt)
                    {
                        if ($apt->delete())
                        {
                            echo '5. delete appoinmnet <br>';
                        }
                    }
                }
            }
            if ($customer->delete())
            {
                echo '6 delete cus...<br>';
            }
        }
    }

    public function actionDeleteAppoinment()
    {
        
    }

    /**
     * process wrong url 
     */
    public function actionProcessURL()
    {



        $biz = Business::model()->findAll();

        if ($biz)
        {
            foreach ($user as $key => $v)
            {
                echo $v->id . '<br>';
            }
        }
    }

    public function actionChat()
    {

        $orders = Orders::model()->findAll();

        foreach ($orders as $or)
        {
            if (NULL == $or->appoint)
            {
                if (!$or->delete())
                {
                    echo 'can not delete ' . $or->order_id . '<br>';
                }
            }
        }
    }

    public function getOpreraHours($test)
    {
        //unserial
        $arr_ip = unserialize($test);



        $arr_result = array();
        $arr_temp   = array();

        $is_push = FALSE;

        if (empty($arr_ip))
        {
            return FALSE;
        }

        //if array only contains one key
        if (count($arr_ip) === 1)
        {
            foreach ($arr_ip as $key => $value)
            {
                $arr_result[$key] = array(
                    'day'  => $key,
                    'time' => $value
                );
            }

            return $arr_result;
        }


        ///duyet tung phan tu
        foreach ($arr_ip as $key => $value)
        {

            //duyet tung phan tu tiep theo
            foreach ($arr_ip as $k => $v)
            {
                if (($value == end($arr_ip)) AND ! array_key_exists($k, $arr_temp))
                {


                    //neu khong ton tai thi
                    $arr_result[$key] = array(
                        'day'  => $key,
                        'time' => $value
                    );
                    $arr_temp[$key]   = $key;


                    $arr_temp[$k] = $k;
                    $is_push      = FALSE;
                }


                //khong xet trung nhau va ngay ( $key ) da dc xu ly roi
                if ($key != $k & !array_key_exists($k, $arr_temp))
                {

                    if ($value == $v)
                    {
                        //neu ton tai  key nay trong mang 
                        if (array_key_exists($key, $arr_temp))
                        {
                            $day              = $arr_result[$key]['day'] . ', ' . $k;
                            $arr_result[$key] = array(
                                'day'  => $day,
                                'time' => $value
                            );
                        }
                        else
                        {
                            //neu khong ton tai thi
                            $arr_result[$key] = array(
                                'day'  => $key . ', ' . $k,
                                'time' => $value
                            );
                            $arr_temp[$key]   = $key;
                        }

                        $arr_temp[$k] = $k;
                        $is_push      = FALSE;
                    }
                    else
                    {
                        $is_push = TRUE;
                    }
                }
            }

            //neu qua mot vong duyet, neu khong trung voi ngay nao thi
            //them mot phan tu moi vao mang.
            if ($is_push && !array_key_exists($key, $arr_temp))
            {
                $arr_result[$key] = array(
                    'day'  => $key,
                    'time' => $value
                );

                //them vao mang da qua xu ly
                $arr_temp[$key] = $key;
                $is_push        = FALSE;
            }
        }

        return $arr_result;
    }

    public function actionFlushCache()
    {


        echo Yii::app()->session['offset_merchant'] . '<br>' .
        Users::model()->getLastMerchant()->id
        . '--' . Yii::app()->session['out_of_merchant'] . '---' . Yii::app()->session['mimispa'];
    }

    public function actionReadExcel()
    {
//include
        $phpExcelPath = Yii::getPathOfAlias('application.extensions.phpexcel');
        include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');

        $file_path = "files/Merchant_batch_creation_1.2.1.1.xlsx";
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');

        if (!file_exists($file_path))
        {
            die('khong ton tai file');
        }
        else
        {
//            die('ton tai');
        }
        $objReader->setReadDataOnly(true);
        $objPHPExcel  = $objReader->load($file_path);
        $objWorksheet = $objPHPExcel->getActiveSheet();

        //vòng lặp từ 67
        $j          = 3;
        $arr_result = array();
        for ($index = 67; $index <= 6127; $index++)
        {
            $merchant_type = $objWorksheet->getCellByColumnAndRow(7, $j)->getValue();
            //cat chuoi
            $arr_strings   = explode(',', $merchant_type);

            $cri = new CDbCriteria();
            foreach ($arr_strings as $string)
            {
                $cri->compare('name', trim($string), FALSE, 'OR');
            }
            $area = Area::model()->findAll($cri);
            if ($area)
            {
                $user = Users::model()->findByPk($index);
                if ($user)
                {
                    foreach ($area as $cate)
                    {
                        $model          = new AreaUser();
                        $model->area_id = $cate->id;
                        $model->user_id = $user->id;
                        $model->save();
                    }
                }
            }
            else
            {
                $arr_result[] = $j;
            }
            //tim user record.
            //kiem tra business gan chua

            $j++;
        }
        print_r($arr_result);
        echo 'done!';
    }

    public function actionT()
    {
        die('xxxx');

        $biz = Business::model()->findByPk(4);
        print_r($biz->listDayOff);
        die;
        echo date('d-m-Y', 1389196800);
        die;
        var_dump(Utils::getBitlyUrl('http://selectivefitness.com/'));
        die;
        $key = array('khoi', 'ngo');


        $ret = new CDbCriteria();

//            $arr = split('', $price);
        foreach ($key as $v)
        {
            $ret->compare('lastname', $v, TRUE, 'OR');
            $ret->compare('firstname', $v, TRUE, 'OR');
        }
//            $ret->compare('firstname', $key, TRUE, 'OR');
        $model = Customer::model()->findAll($ret);
        foreach ($model as $v)
        {
            echo $v->firstname;
        }

        die;
//            var_dump($model);die;
        print_r(Utils::minuteStep(5, '', ''));
        die;
        print_r(unserialize('a:1:{s:6:"Monday";a:3:{s:7:"Morning";a:2:{i:0;s:8:"01:00 AM";i:1;s:8:"05:00 AM";}s:9:"Afternoon";a:2:{i:0;s:8:"05:00 AM";i:1;s:8:"10:00 AM";}s:7:"Evening";a:2:{i:0;s:8:"01:00 PM";i:1;s:8:"05:00 PM";}}}'));
        die;
        echo strtotime('3/Dec/2013');
        die;
        echo Utils::getResetTimeStamp(strtotime('1 Dec, 2013'));
        die;
//        $array1 = array("a" => "green", "red", "blue", "red");
//$array2 = array("b" => "green", "yellow", "red");
//$result = array_diff($array1, $array2);
//
//print_r($result);die;
        $monday = array(
            'morning'   => array('start' => '8:00', 'end' => '10:00'),
            'afternoon' => array('start' => '8:00', 'end' => '10:00'),
            'evening'   => array('start' => '8:00', 'end' => '10:00'),
        );
        $tueday = array(
            'morning'   => array('start' => '7:00', 'end' => '9:00'),
            'afternoon' => array('start' => '8:00', 'end' => '10:00'),
            'evening'   => array('start' => '8:00', 'end' => '10:00'),
        );

        $a   = Array('start_Morning' => '12:00 AM', 'end_Morning' => '12:00 AM', 'start_Afternoon' => '12:00 AM', 'end_Afternoon' => '12:00 AM', 'start_Evening' => '12:00 AM', 'end_Evening' => '12:00 AM');
        $b   = Array('start_Morning' => '12:15 AM', 'end_Morning' => '12:15 AM', 'start_Afternoon' => '12:15 AM', 'end_Afternoon' => '12:15 AM', 'start_Evening' => '12:00 AM', 'end_Evening' => '12:00 AM');
        print_r(array_diff($b, $a));
        die;
        $arr = array();
        foreach ($tueday as $key => $v)
        {
            $arr[]['start_' . $key] = $v['start'];
            $arr[]['end_' . $key]   = $v['end'];
        }
        print_r($arr);
        die;

//search different
//        $arr_d = array_diff($tueday,$monday);
        $result = array_diff($monday['morning']);
        print_r($result);
        die;
        return (array_diff($monday, $tueday));
        die;
        $arr    = array('khoai' => array(0, 1)
            , 'ngo'   => array(2, 3)
            , 'san');
        print_r(next($arr['khoai']));
        die;
//         $long_url = $this->getAsoluteUrl();
//        phpinfo();
        $bitly  = Yii::app()->bitly->shorten('http://dantri.com')->getResponseData();
//            ->getResponseData();
//        ->getResponseData()
//        $t=$bitly->getResponseData();
//        echo 'xxx';
//        ob_clean();
//        var_dump($bitly);

        $json = CJSON::decode($bitly);
        echo $json['data']['url'];

        echo 'xxx';
        die;
//        var_dump($bitly);die;
        $a      = $bitly->get('url', null, null, null);
        $encode = json_decode($bitly->getResponseData());
//        var_dump($encode);die;
//        print_r(unserialize('a:5:{s:39:"hauth_session.google.token.access_token";s:86:"s:78:"ya29.1.AADtN_Wdcqso6kRWrEcSJUlK-1uMoNsOThfDUe7SWFbZrngQbusI7RE1c1oIIRDK7obN5Ho";";s:40:"hauth_session.google.token.refresh_token";s:7:"s:0:"";";s:37:"hauth_session.google.token.expires_in";s:7:"i:3596;";s:37:"hauth_session.google.token.expires_at";s:13:"i:1385700898;";s:33:"hauth_session.google.is_logged_in";s:4:"i:1;";}'));die;
//       $this->render('index');
    }

    public function actionT2()
    {
        $bitly  = Yii::app()->bitly->shorten('http://dantri.com');
//        var_dump($bitly);die;
        $a      = $bitly->get('url', null, null, null);
        echo $a;
        die;
        $social = new Social();
        $t      = $social->getSession(Social::GOOGLE);
        echo $t;

//        $so=$social->getInstanceSocial(Social::GOOGLE);
//        $json_tocen=  json_encode($so->getAccessToken());
//        echo $json_tocen;
    }

    public function genTime($time1, $time2)
    {
        if (strtotime($time1) >= strtotime($time2))
        {
            return TRUE;
        }
        return FALSE;
    }

    /**
     * 
     * @param int $id_user id of staff
     * @param string $day ex:2013-07-26
     * @param string $start_time start time ex: 08:00
     * @param string $end_time end time ex: 08:00
     * @return boolean <b>TRUE</b> if staff validate or <b>FALSE</b> otherwise
     */
    public function checkTimeWordByDay($id_user, $day, $apt_start_time, $apt_end_time)
    {
        $model = SchedulesUser::model()->find('user_id=:userid AND date=:date', array(
            ':userid' => $id_user,
            ':date'   => $day
        ));
        if ($model == NULL)
        {//check time default
            $day_of_week = date('w', strtotime($day));

            $default = SchedulesDefault::model()->find('day=:day', array(
                ':day' => $day_of_week
            ));
            if ($default == NULL)
            {
                return TRUE;
            }
            else
            {
                $check_time = AppointHeper::compareWorkTime($apt_start_time, $apt_end_time, AppointHeper::minutesToTime($default->work_start), AppointHeper::minutesToTime($default->work_end), AppointHeper::minutesToTime($default->lunch_start), AppointHeper::minutesToTime($default->lunch_end));
                if ($check_time)
                {
                    return TRUE;
                }
                else
                {
                    return FALSE;
                }
            }
        }
        else
        {
            if ($model->type != SchedulesUser::WORK_DAY)
            {
                return FALSE;
            }
            else
            {
                $check_time = Utils::compareWorkTime($apt_start_time, $apt_end_time, AppointHeper::minutesToTime($model->work_start), AppointHeper::minutesToTime($model->work_end), AppointHeper::minutesToTime($model->lunch_start), AppointHeper::minutesToTime($model->lunch_end));
                if ($check_time)
                {
                    return TRUE;
                }
                else
                {
                    return FALSE;
                }
            }
        }
    }

    public function actionMail()
    {
        $mail          = new MyEmail();
        $mail->body    = 'test send from webmaster body';
        $mail->subject = 'test send from webmaster';
        $mail->to      = 'anhduc.bkhn@gmail.com';
        $mail->easySend();
    }

    function actionMadeGroup()
    {
        $staffs = Users::model()->findAll('type=:t', array(':t' => Users::TYPE_STAFF));
//        echo count($staffs);die;
        foreach ($staffs as $staff)
        {
            $check_group = GroupUser::model()->find('user_id=:u', array(':u' => $staff->id));
            if (!$check_group)
            {
                echo $staff->id . ", ";
                $label           = new GroupUser();
                $label->group_id = 0;
                $label->user_id  = $staff->id;
                $label->save();
            }
        }
    }

}

/**
 * End of Test
 */
